package app.circlerequest;


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;



/**
 * 这个类用于服务器主动向硬件发送的向下行的数据请求
 * @author haoqi
 *2017-10-20 17:17:53
 */
public class ServerDownriverMsgHttp {

	
//	private static final Logger logger = LogManager.getLogger(ServerDownriverMsgHttp.class); 
	
	/**
	 * 
	 * @param url
	 * @param data
	 * @param time
	 */
	@SuppressWarnings("finally")
	public String HttpRequest(String url,String data,String time){
		HttpURLConnection urlConnection=null;
		StringBuffer buf = new StringBuffer();
		String msg ="";
		try {
			URL requestUrl = new URL(url);
			
			urlConnection = (HttpURLConnection) requestUrl.openConnection();
			
			urlConnection.setDoOutput(true);
			
			urlConnection.setDoInput(true);
			
			urlConnection.setUseCaches(false);
			
			urlConnection.setRequestMethod("POST");
			urlConnection.setRequestProperty("mess", data);
			urlConnection.setRequestProperty("d_time", time);
			urlConnection.connect();
			
			InputStream inputStream = urlConnection.getInputStream();

			if (inputStream!=null) {
				byte[] resp = new byte[18];
				
				int len=0;
				while((len=inputStream.read(resp))>0){
					buf.append(new String(resp, 0, len));
				}
				
				msg = buf.toString();
			}
		
			
			
	
		} catch (Exception e) {
			
			System.out.println("httpRequest失败！");
			
		}finally {
		
			urlConnection.disconnect();	
			return msg;
		}
		
		
	}
	
	
	/**
	 * write log
	 * @param path
	 * @param content
	 */
	private void writeLog(String path,String content){
		
		try {
			
			OutputStream fos = new FileOutputStream(new File(path),true);
			
			Date date = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String dateStr = sdf.format(date);
			
			fos.write((content+" "+dateStr+"\r\n").getBytes());
			fos.flush();
			
			fos.close();
			
			
		} catch (Exception e) {
			System.out.println("Writelog is failed: "+path);
		}
		
	}
	
	
}
